package com.example.nettydemo.simple;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * Netty Server Channel 处理器
 *
 * @author SuperWein
 */
@Slf4j
public class ChannelServerHandler extends ChannelInboundHandlerAdapter {

    private static final String ascii2 = String.valueOf((char)2);
    private static final String ascii3 = String.valueOf((char) 3);

    @Override
    public void channelActive(ChannelHandlerContext context) throws Exception {
        log.info("The client from {} is connected success.", context.channel().remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext context) throws Exception {
        log.info("The client from {} is disConnected.", context.channel().remoteAddress());
    }

    @Override
    public void channelRead(ChannelHandlerContext context, Object msg) throws Exception {
        log.info("Receive message [{}] from client {}", msg, context.channel().remoteAddress());
        // 先得到channel，再写入通道，然后通过flush刷新通道把消息发出去
        context.channel().writeAndFlush(ascii2 + "Hello client, I'm server." + ascii3);
        // Netty服务端的通道初始化方法配置了多个handler时，调用该方法将消息传递给下一个handler处理
        // context.fireChannelRead(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext context, Throwable cause) throws Exception {
        log.error("Channel server handler has an exception", cause);
        context.close();
    }
}
